import pymysql
from pymysql.cursors import DictCursor
from twisted.enterprise import adbapi
from dbutils.pooled_db import PooledDB
from .handler_cls import DBUtilSyncMysqlHandler, TwistedAsyncMysqlHandler


__all__ = ['DBUtilSyncMysqlConnectionPoolMaker', 'TwistedAsyncMysqlConnectionPoolMaker']


class DBUtilSyncMysqlConnectionPoolMaker(object):

    def __init__(self, host, port, user, password, db, charset='utf8', cursorclass=DictCursor, **kwargs):
        self.config = {
            'host': host,
            'port': port,
            'user': user,
            'password': password,
            'db': db,
            'charset': charset,
            'cursorclass': cursorclass
        }
        self.config.setdefault('setsession', ['SET AUTOCOMMIT = 1'])
        self._db_pool = PooledDB(creator=pymysql, **self.config, **kwargs)

    def _get_db_pool(self):
        try:
            self._db_pool.connection()
        except Exception as e:
            raise e
        else:
            return self._db_pool

    def __call__(self):
        return DBUtilSyncMysqlHandler(pool=self._get_db_pool())


class TwistedAsyncMysqlConnectionPoolMaker(object):

    def __init__(self, host, port, user, password, db, charset='utf8', cursorclass=DictCursor, **kwargs):
        self.config = {
            'host': host,
            'port': port,
            'user': user,
            'password': password,
            'db': db,
            'charset': charset,
            'cursorclass': cursorclass
        }
        self._db_pool = adbapi.ConnectionPool('pymysql', **self.config, **kwargs)

    def get_db_pool(self):
        try:
            self._db_pool.connect()
        except Exception as e:
            raise e
        else:
            return self._db_pool

    def __call__(self, errback=None):
        return TwistedAsyncMysqlHandler(pool=self.get_db_pool(), errback=errback)





